#!/usr/bin/env python2
# -*- conding: utf-8 -*-


from Ump import utils
from Ump.common import exception
from Ump.objs.db import models
from Ump.objs.db.models import ScheduleJob


def reload_scheduler():
    mod = __import__('Ump.schedule.main', globals(), locals(), [''])
    #print  "*******mod#### *******" , mod
    _scheduler = getattr(mod, '_scheduler')
    #print  "##################_scheduler######" , _scheduler
    return _scheduler


class ScheduleApi(object):

    def __init__(self, is_op_schedule=True):
        self.is_op_schedule = is_op_schedule

    def create_job(self, values):

        job = models.ScheduleJob(values).save()

        if self.is_op_schedule:
            _scheduler = reload_scheduler()
            _scheduler.add_job(job)
        return job
    
    def delete_job(self, job_id):
        sjob = self.get_one(job_id)
    
        _scheduler = reload_scheduler()
        _scheduler.remove_job(sjob.id)
        sjob.delete()
        return True
    
    def update_job(self, job_id, values):
        sjob = self.get_one(job_id)
    
        sjob.update(values)

        if self.is_op_schedule:
            _scheduler = reload_scheduler()
            _scheduler.reschedule_job(sjob)
        return sjob
    
    def get_one(self, job_id):
        job = ScheduleJob.query.get(job_id)
        if not job:
            raise exception.NotFound(job_id=job_id)
        return job


